package com.book.business.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.book.breakage.entity.Back;
import com.book.breakage.service.BackService;
import com.book.business.entity.BookIndent;
import com.book.business.entity.BookSell;
import com.book.business.service.BookIndentService;
import com.book.business.service.BookSellService;
import com.book.common.annotation.ControllerEndpoint;
import com.book.common.annotation.Log;
import com.book.common.controller.BaseController;
import com.book.common.entity.FebsConstant;
import com.book.common.entity.FebsResponse;
import com.book.common.entity.QueryRequest;
import com.book.common.utils.FebsUtil;
import com.book.common.utils.SortUtil;
import com.book.common.utils.WareBook;
import com.book.management.entity.Revocation;
import com.book.management.service.RevocationService;
import com.book.publishing.entity.Bookman;
import com.book.publishing.service.BookmanService;
import com.book.stat.entity.BreakageStat;
import com.book.stat.entity.SellStat;
import com.book.stat.service.BreakageStatService;
import com.book.stat.service.SellStatService;
import com.book.system.entity.Money;
import com.book.system.entity.User;
import com.book.system.service.IUserService;
import com.book.system.service.MoneyService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Map;

/**
 * @Author: 盛佳帅
 * @Description: 20173953
 */

@Controller
public class BookIndentController extends BaseController {
    @Autowired
    BookIndentService bookIndentService;
    @Autowired
    IUserService userService;
    @Autowired
    SellStatService sellStatService;
    @Autowired
    BackService backService;
    @Autowired
    BookSellService bookSellService;
    @Autowired
    BreakageStatService breakageStatService;
    @Autowired
    MoneyService moneyService;
    @Autowired
    RevocationService revocationService;
    @Autowired
    BookmanService bookmanService;

    @GetMapping(FebsConstant.VIEW_PREFIX + "business/bookIndent")
    public String bookIndentIndex() {
        return FebsUtil.view("business/indent/bookIndentList");
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "business/bookIndent/update/{id}")
    public String bookIndentUpdate(@PathVariable Integer id, ModelMap modelMap) {
        BookIndent bookIndent = this.bookIndentService.getById(id);
        modelMap.put("bookIndent", bookIndent);
        return FebsUtil.view("business/indent/bookIndentUpdate");
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "business/bookIndent/back/{id}")
    public String bookIndentBack(@PathVariable Integer id, ModelMap modelMap) {
        BookIndent bookIndent = this.bookIndentService.getById(id);
        modelMap.put("bookIndent", bookIndent);
        return FebsUtil.view("business/indent/bookIndentBack");
    }

    @GetMapping("bookIndent")
    @ResponseBody
    public FebsResponse bookIndentList(BookIndent bookIndent) {
        return new FebsResponse().success().data(this.bookIndentService.findBookIndent(bookIndent));
    }


    @GetMapping("bookIndent/sort/{pubid}")
    @ResponseBody
    public FebsResponse bookIndentListSort(@PathVariable String pubid) {
        List<BookIndent> bookIndentList = bookIndentService.bookIndentSort(pubid);
        List<BookIndent> bookIndents = new ArrayList<>();
        for (int i = 0; i < bookIndentList.size(); i++) {
            List<BookIndent> list = bookIndentService.list(new QueryWrapper<BookIndent>().lambda().eq(BookIndent::getBookname, bookIndentList.get(i).getBookname()));
            if (list.size() == 1) {
                for (int j = 0; j < list.size(); j++) {
                    bookIndents.add(list.get(j));
                }
            } else {
                BookIndent bookIndent = new BookIndent().setNumber(0);
                for (int j = 0; j < list.size(); j++) {
                    bookIndent.setNumber(bookIndent.getNumber() + list.get(j).getNumber());
                }
                bookIndent.setBookname(bookIndentList.get(i).getBookname())
                        .setType(bookIndentList.get(i).getType());
                bookIndents.add(bookIndent);
            }
        }
        return new FebsResponse().success().data(bookIndents);
    }

    @Log("访问订单信息")
    @GetMapping("bookIndent/list")
    @ResponseBody
    public FebsResponse bookIndentIPage(QueryRequest request, BookIndent bookIndent) {
        Map<String, Object> dataTable = getDataTable(this.bookIndentService.pageBookIndent(request, bookIndent));
        return new FebsResponse().success().data(dataTable);
    }

    @Log("订单-修改")
    @PostMapping("bookIndent/update")
    @ResponseBody
    @RequiresPermissions("bookIndent:update")
    @ControllerEndpoint(operation = "修改订单信息成功", exceptionMessage = "修改订单信息失败")
    public FebsResponse bookIndentUpdate(BookIndent bookIndent) {
        if ("1".equals(bookIndent.getFlag())) {
            return new FebsResponse().message("这是已经完成的订单，不能修改！");
        }
        if (!"0".equals(bookIndent.getStatus())) {
            return new FebsResponse().message("该订单已经发货，不能修改收货信息！");
        }
        User user = getCurrentUser();
        user.setMobile(bookIndent.getPhone()).setAddress(bookIndent.getAddress());
        userService.updateUser(getCurrentUser());
        bookIndentService.updateBookIndent(bookIndent);
        return new FebsResponse().success();
    }

    /**
     * @Description: 未发货
     * @Date: 2021/1/26
     */
    @Log("订单-取消（未发货）")
    @PostMapping("bookIndent/backOne")
    @ResponseBody
    @RequiresPermissions("bookIndent:back")
    @ControllerEndpoint(operation = "订单取消成功", exceptionMessage = "订单取消失败")
    public FebsResponse bookIndentBackOne(BookIndent bookIndent) {
        System.out.println(bookIndent);
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM");
        Calendar calendar = Calendar.getInstance();
        String yearAndMonths = format.format(calendar.getTime());
        String[] yearAndMonth = yearAndMonths.split("-");
        //通过发货状态和退书状态拿到相同名称的书籍信息
        BookIndent indent = bookIndentService.getById(bookIndent.getId());
        // 本年是否有相同书籍的退书信息
        Revocation revocation = revocationService.getOne(new QueryWrapper<Revocation>().lambda()
                .eq(Revocation::getBookname, bookIndent.getBookname()).eq(Revocation::getYear, yearAndMonth[0]));
        // 加入统计信息
        if (revocation == null) {
            revocation = new Revocation()
                    .setBookname(bookIndent.getBookname())
                    .setPubid(bookIndent.getPubid())
                    .setNumber(bookIndent.getNumber())
                    .setBooktype(bookIndent.getType())
                    .setBookmoney(bookIndent.getBookmoney())
                    .setYear(yearAndMonth[0]);
            revocationService.addRevocation(revocation);
        } else {
            revocation.setNumber(revocation.getNumber() + bookIndent.getNumber());
            revocationService.updateRevocation(revocation);
        }
        // 拿到对应订单
        Money money = moneyService.getOne(new QueryWrapper<Money>().lambda().eq(Money::getBookindentid, indent.getBookindentid()));
        money.setType("2");
        User user = getCurrentUser();
        user.setMoney(user.getMoney() + indent.getMoney());
        WareBook.wareBookChange(bookIndent.getBookname(), "增加", bookIndent.getNumber());
        bookIndentService.removeById(bookIndent.getId());
        // 拿到架存管理书籍
        moneyService.updateMoney(money);
        userService.updateMoney(user);
        return new FebsResponse().success();
    }

    /**
     * @Description: 已发货
     * @Date: 2021/1/26
     */
    @Log("订单-取消（已发货）")
    @PostMapping("bookIndent/backTwo")
    @ResponseBody
    @RequiresPermissions("bookIndent:back")
    @ControllerEndpoint(operation = "退书申请成功", exceptionMessage = "退书申请失败")
    public FebsResponse bookIndentBackTwo(BookIndent bookIndent) {
        BookIndent one = bookIndentService.getById(bookIndent.getId());
        if ("1".equals(one.getBackstatus())) {
            return new FebsResponse().message("该订单已经申请报损，请耐心等待！");
        }
        if ("2".equals(one.getBackstatus())) {
            return new FebsResponse().message("该订单已经强制完成，不能退书！");
        }
        if ("3".equals(one.getBackstatus())) {
            return new FebsResponse().message("该订单正在申请退书中...");
        }
        Back back = new Back()
                .setIndentid(bookIndent.getId())
                .setBookname(bookIndent.getBookname())
                .setBookmoney(bookIndent.getBookmoney())
                .setBooktype(bookIndent.getType())
                .setMessage(bookIndent.getBackmessage())
                .setPrincipal(bookIndent.getUsername())
                .setPubid(bookIndent.getPubid())
                .setUsername(getCurrentUser().getUsername())
                .setNumber(bookIndent.getNumber())
                .setStatus("0");
        backService.backAdd(back);
        bookIndent.setBackstatus("1");
        bookIndentService.updateBookIndent(bookIndent);
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM");
        Calendar calendar = Calendar.getInstance();
        String yearAndMonths = format.format(calendar.getTime());
        String[] yearAndMonth = yearAndMonths.split("-");
        BreakageStat breakageStat = new BreakageStat()
                .setBreakageid((bookIndent.getId()).toString())
                .setBookfrom("2")
                .setBookname(bookIndent.getBookname())
                .setBooktype(bookIndent.getType())
                .setPubid(bookIndent.getPubid())
                .setBookmoney(bookIndent.getBookmoney())
                .setNumber(bookIndent.getNumber())
                .setYear(yearAndMonth[0])
                .setMonth(yearAndMonth[1])
                .setTotalmoney(bookIndent.getBookmoney() * bookIndent.getNumber())
                .setOmit("0");
        breakageStatService.addCount(breakageStat);
        return new FebsResponse().success();
    }

    @Log("订单-收货")
    @PostMapping("bookIndent/flag/{ids}")
    @ResponseBody
    @RequiresPermissions("bookIndent:flag")
    @ControllerEndpoint(operation = "收货成功", exceptionMessage = "收货失败")
    public FebsResponse bookIndentFlag(@PathVariable String ids) {
        String[] attr = ids.split(",");
        //这里拿删除方法，得到对应ids的对象信息集合
        List<BookIndent> bookIndents = bookIndentService.deleteBookIndent(attr);
        for (int i = 0; i < bookIndents.size(); i++) {
            if ("1".equals(bookIndents.get(i).getBackstatus())) {
                return new FebsResponse().message("该订单正在申请报损中...");
            }
            if ("2".equals(bookIndents.get(i).getBackstatus())) {
                return new FebsResponse().message("该订单已经完成，无需再次收货");
            }
            if ("3".equals(bookIndents.get(i).getBackstatus())) {
                return new FebsResponse().message("该订单正在申请退书中...");
            }
            if ("1".equals(bookIndents.get(i).getFlag())) {
                return new FebsResponse().message("不能重复签收订单！");
            }
            if ("0".equals(bookIndents.get(i).getStatus())) {
                return new FebsResponse().message("该订单还未发货！");
            }
            bookIndents.get(i).setFlag("1");
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Calendar calendar = Calendar.getInstance();
            String finish = format.format(calendar.getTime());
            bookIndents.get(i).setFinishtime(finish);
            bookIndentService.updateBookIndent(bookIndents.get(i));
            QueryWrapper<Bookman> bookmanQueryWrapper = new QueryWrapper<>();
            bookmanQueryWrapper.eq("pubname", bookIndents.get(i).getPubid());
            Bookman bookman = bookmanService.getOne(bookmanQueryWrapper);
            if (bookman != null) {
                bookman.setSalenumber(bookman.getSalenumber() + bookIndents.get(i).getNumber());
                bookmanService.updateBookman(bookman);
            }
            //做统计用
            QueryWrapper<SellStat> sellStatQueryWrapper = new QueryWrapper<>();
            sellStatQueryWrapper.eq("location", bookIndents.get(i).getAddress());
            sellStatQueryWrapper.eq("year", bookIndents.get(i).getYear());
            SellStat sellStat = sellStatService.getOne(sellStatQueryWrapper);
            if (sellStat == null) {
                sellStat = new SellStat()
                        .setLocation(bookIndents.get(i).getAddress())
                        .setNumber(bookIndents.get(i).getNumber())
                        .setYear(bookIndents.get(i).getYear());
                sellStatService.addSellStat(sellStat);
            } else {
                sellStat.setNumber(sellStat.getNumber() + bookIndents.get(i).getNumber());
                sellStatService.updateSellStat(sellStat);
            }
        }
        return new FebsResponse().success();
    }

    @Log("订单-发货")
    @PostMapping("bookIndent/status/{ids}")
    @ResponseBody
    @RequiresPermissions("bookIndent:status")
    @ControllerEndpoint(operation = "发货成功", exceptionMessage = "发货失败")
    public FebsResponse bookIndentStatus(@PathVariable String ids) {
        String[] attr = ids.split(",");
        //这里拿删除方法，得到对应ids的对象信息集合
        List<BookIndent> bookIndents = bookIndentService.deleteBookIndent(attr);
        for (int i = 0; i < bookIndents.size(); i++) {
            if ("1".equals(bookIndents.get(i).getFlag())) {
                return new FebsResponse().message("该订单已经完成，不能进行发货！");
            }
            if (!"0".equals(bookIndents.get(i).getStatus())) {
                return new FebsResponse().message("该订单已经发货，请勿重复发货！");
            }
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Calendar calendar = Calendar.getInstance();
            //将本地时间转换成string类型，传回前端
            String status = format.format(calendar.getTime());
            bookIndents.get(i).setStatus(status);
            bookIndentService.updateBookIndent(bookIndents.get(i));
        }
        return new FebsResponse().success();
    }

    @Log("订单-删除")
    @PostMapping("bookIndent/delete/{ids}")
    @ResponseBody
    @ControllerEndpoint(operation = "删除订单信息成功", exceptionMessage = "删除订单信息失败")
    public FebsResponse bookIndentdelete(@PathVariable String ids) {
        String[] attr = ids.split(",");
        List<BookIndent> bookIndents = bookIndentService.deleteBookIndent(attr);
        for (int i = 0; i < bookIndents.size(); i++) {
            if (!"1".equals(bookIndents.get(i).getFlag())) {
                return new FebsResponse().message("该订单还未完成，不能删除。");
            }
            bookIndents.get(i).setOmit("0");
            bookIndentService.updateBookIndent(bookIndents.get(i));
        }
        return new FebsResponse().success();
    }
}

